package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.dtos.WmNewsDto;
import com.heima.model.common.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.common.wemedia.enums.WemediaConstants;
import com.heima.model.common.wemedia.pojos.WmMaterial;
import com.heima.model.common.wemedia.pojos.WmNews;
import com.heima.model.common.wemedia.pojos.WmNewsMaterial;
import com.heima.model.common.wemedia.pojos.WmUser;
import com.heima.utils.threadLocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.*;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired(required = false)
    private WmMaterialMapper wmMaterialMapper;


    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;


    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //获取当前登陆人的信息
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.分页条件查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //状态精确查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道精确查询
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //时间范围查询
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }
        //关键字模糊查询
        if (dto.getKeyword() != null) {
            lambdaQueryWrapper.like(WmNews::getLabels, dto.getKeyword());
        }
        //查询当前登录用户的文章
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());
        //发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        page = page(page, lambdaQueryWrapper);
        //3.结果返回
        ResponseResult responseResult = new ResponseResult(dto.getPage(), dto.getSize(), page.getTotal());


        responseResult.setData(page.getRecords());

        return responseResult;
    }

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //判断参数
        if (dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getType() == -1) {
            dto.setType(null);
        }

        //1.保存或修改文章
        WmNews wmNews = new WmNews();
        //属性拷贝 属性名词和类型相同才能拷贝
        BeanUtils.copyProperties(dto, wmNews);


        //封装images到wmnews实体中
        List<String> images = dto.getImages();
        //把转成字符串
        if (images != null && images.size() > 0) {
            //利用工具类把集合转化成字符串，并且每个之间用逗号间隔
            String imgStr = StringUtils.join(images, ",");
            wmNews.setImages(imgStr);
        }
        //3.执行修改或者保存
        saveorUpdateNews(wmNews);

        //2.如果是草稿
        if (dto.getStatus() == 0) {
            //则执行返回
            return ResponseResult.okResult(null);
        }

        //4.关联中间表，操作wm_news_marterial表
        //4.0 要从内容中把图片给抽取出来
        List imageList = chouquImageList(wmNews);

        //4.1 内容中图片与文章的关系
        contentImageToNews(wmNews, imageList, WemediaConstants.WM_CONTENT_REFERENCE);

        //4.2 封面图片与文章的关系
        fengmianImageToNews(wmNews, dto, imageList, WemediaConstants.WM_COVER_REFERENCE);

        //5.异步调用文章审核业务
        // wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        //调用延迟队列，添加任务
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;


    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 上下架
     *
     * @param dto
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
       if (dto.getId()==null){
           return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
       }
       //1.根据id查询文章
        WmNews wmNews = getById(dto.getId());
       if (wmNews==null){
           return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不存在");
       }
       //2.查询 是否已经是发布状态
       if (wmNews.getStatus()!=WmNews.Status.PUBLISHED.getCode()){
           return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"当前文章不是发布状态，不可以操作");
       }
       //3.修改文章状态
        wmNews.setEnable(dto.getEnable());
        boolean flag = updateById(wmNews);
        //4.发送消息
        if (flag) {
            Map messageMap = new HashMap();
            messageMap.put("articleId", wmNews.getArticleId());
            messageMap.put("enable", wmNews.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(messageMap));

        }
        return ResponseResult.okResult("文章上下架成功");

    }


    /**
     * 根据文章id回显信息
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult selectById(Integer id) {
        //判断参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmNews wmNews = wmNewsMapper.selectById(id);
        WmNewsDto wmNewsDto = new WmNewsDto();
        BeanUtils.copyProperties(wmNews, wmNewsDto);
        return ResponseResult.okResult(wmNews);

    }


    /**
     * 根据id删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //判断参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        WmNews wmNews = wmNewsMapper.selectById(id);
        Short status = wmNews.getStatus();

        if (status == 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章已经发布，不能删除");
        }
        if (status == 1 || status == 3 || status == 4 || status == 2) {
            wmNews.setEnable((short) 0);
            wmNewsMapper.deleteById(id);
            return ResponseResult.okResult("删除成功");
        }
        //删除minio数据
        wmNewsMapper.deleteById(id);
        return ResponseResult.okResult("删除成功");

    }


    /**
     * 抽取的第四个方法，关联封面图片与文章的关系，操作中间表
     * 如果封面类型是自动的话，从文章内容中图片进行操作
     * 如果文章内容图片个数大于1，小于3的话，则认为单图
     * 如果文章内容图片个数大于等于3的话，则认为多图
     * 如果文章内容图片个数，则认为是无图
     *
     * @param wmNews
     * @param type
     */
    private void fengmianImageToNews(WmNews wmNews, WmNewsDto dto, List imageList, short type) {
        //1.获取封面图片
        List<String> images = dto.getImages();

        //自动
        if (dto.getType() == null) {
            if (imageList.size() >= 1 && imageList.size() < 3) {
                //取出第一张图片作为封面
                images = (List<String>) imageList.stream().limit(1).collect(Collectors.toList());
                //单图设置类型
                wmNews.setType((short) 1);
            } else if (imageList.size() >= 3) {
                images = (List<String>) imageList.stream().limit(3).collect(Collectors.toList());
                //多图设置类型
                wmNews.setType((short) 3);
            } else {
                wmNews.setType((short) 0);
            }

            wmNews.setImages(StringUtils.join(images, ","));
            updateById(wmNews);
        }
        //否则，直接插入到中间表中
        saveNewsMaterial(wmNews, type, images);
    }

    /**
     * 第五个抽取方法
     *
     * @param wmNews
     * @param type
     * @param images
     */
    private void saveNewsMaterial(WmNews wmNews, short type, List<String> images) {
        //1.判断imageList是否有值
        if (images != null && images.size() > 0) {
            //根据地址集合去查询素材表
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images));
            //2.要从素材集合中只抽取出相对应的id集合
            List<Integer> materialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            /**
             * 参数1表示素材id集合
             * 参数2表示文章id
             * 参数3表示引用类型
             */
            wmNewsMaterialMapper.saveRelations(materialIds, wmNews.getId(), type);
        }
    }

    /**
     * 第三个抽取方法，关联内容中的图片与文章的关系，操作中间表
     *
     * @param wmNews    文章实体
     * @param imageList 内容中抽取的图片集合,图片地址集合
     * @param type      引用类型，0表示内容引用 1表示封面引用
     */
    private void contentImageToNews(WmNews wmNews, List imageList, Short type) {

        saveNewsMaterial(wmNews, type, imageList);
    }

    /**
     * 第二个抽取方法，为了从文章内容中抽取图片集合
     *
     * @param wmNews
     * @return
     */
    private List chouquImageList(WmNews wmNews) {

        List imageList = new ArrayList();

        //1.获取内容
        String content = wmNews.getContent();
        //2.转化list类型
        List<Map> list = JSON.parseArray(content, Map.class);
        for (Map map : list) {
            if (map.get("type").equals("image")) {
                String value = (String) map.get("value");
                imageList.add(value);
            }
        }
        return imageList;

    }

    /**
     * 第一个抽取方法，修改或者保存
     *
     * @param wmNews
     */
    private void saveorUpdateNews(WmNews wmNews) {
        //补全属性
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        WmUser user = WmThreadLocalUtil.getUser();
        wmNews.setUserId(user.getId());
        //1.判断是否是包含id
        if (wmNews.getId() != null) {
            //修改业务
            //删除中间表
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //修改文章表
            updateById(wmNews);
        } else {
            //新增
            save(wmNews);
        }
    }

}
